import Flutter
import UIKit
import Vision

public class IamgeqrFlutterPlugin: NSObject, FlutterPlugin, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    private var result: FlutterResult?
    private var viewController: UIViewController?
    
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "iamgeqr_flutter_plugin", binaryMessenger: registrar.messenger())
        let instance = IamgeqrFlutterPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
        
        // 移除对 keyWindow 的依赖，统一在弹出时动态获取顶层控制器
        // if let viewController = UIApplication.shared.keyWindow?.rootViewController {
        //     instance.viewController = viewController
        // }
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        self.result = result
        
        switch call.method {
        case "getPlatformVersion":
            result("iOS " + UIDevice.current.systemVersion)
        case "imageScanQr":
            openImagePicker()
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    private func openImagePicker() {
        // 使用主线程 + 顶层控制器进行 present，兼容 iOS 13+ 多场景
        DispatchQueue.main.async {
            guard let presenter = self.getTopViewController() else {
                self.result?("无法获取顶层视图用于弹出相册")
                return
            }
            let imagePickerController = UIImagePickerController()
            imagePickerController.delegate = self
            imagePickerController.sourceType = .photoLibrary
            imagePickerController.modalPresentationStyle = .fullScreen
            presenter.present(imagePickerController, animated: true, completion: nil)
        }
    }
    
    // 获取当前顶层可用的视图控制器（兼容 iOS 13+ 场景）
    private func getTopViewController() -> UIViewController? {
        if #available(iOS 13.0, *) {
            let scenes = UIApplication.shared.connectedScenes
                .compactMap { $0 as? UIWindowScene }
                .filter { $0.activationState == .foregroundActive }
            for scene in scenes {
                if let window = scene.windows.first(where: { $0.isKeyWindow }) {
                    var top: UIViewController? = window.rootViewController
                    while let presented = top?.presentedViewController { top = presented }
                    if let nav = top as? UINavigationController { top = nav.visibleViewController }
                    if let tab = top as? UITabBarController { top = tab.selectedViewController }
                    return top
                }
            }
            // 兜底
            var top: UIViewController? = UIApplication.shared.windows.first?.rootViewController
            while let presented = top?.presentedViewController { top = presented }
            if let nav = top as? UINavigationController { top = nav.visibleViewController }
            if let tab = top as? UITabBarController { top = tab.selectedViewController }
            return top
        } else {
            var top = UIApplication.shared.keyWindow?.rootViewController
            while let presented = top?.presentedViewController { top = presented }
            if let nav = top as? UINavigationController { top = nav.visibleViewController }
            if let tab = top as? UITabBarController { top = tab.selectedViewController }
            return top
        }
    }
    
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        
        guard let image = info[.originalImage] as? UIImage else {
            self.result?("No image selected")
            return
        }
        
        scanQRCode(image)
    }
    
    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
        self.result?("Cancelled")
    }
    
    private func scanQRCode(_ image: UIImage) {
        guard let cgImage = image.cgImage else {
            self.result?("Failed to get CGImage")
            return
        }
        
        let request = VNDetectBarcodesRequest { (request, error) in
            if let error = error {
                self.result?(error.localizedDescription)
                return
            }
            
            guard let observations = request.results as? [VNBarcodeObservation],
                  let firstResult = observations.first,
                  let payload = firstResult.payloadStringValue else {
                self.result?("No QR code found")
                return
            }
            
            self.result?(payload)
        }
        
        let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
        
        do {
            try handler.perform([request])
        } catch {
            self.result?(error.localizedDescription)
        }
    }
}
